package com.azt.front.action.freemarker;

import com.azt.api.pojo.Advertise;
import com.azt.api.pojo.AdvertiseImg;
import com.azt.api.service.AdvertiseService;
import com.azt.utils.FreemarkerUtils;
import com.xiaoleilu.hutool.util.StrUtil;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告模板
 * Created by Snowler on 2016/12/8.
 */
@Component("advertise_template")
public class AdvertiseDirective implements TemplateDirectiveModel {

    @Autowired
    private AdvertiseService advertiseService;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] arg2, TemplateDirectiveBody body)
            throws TemplateException, IOException {


        String code = DirectiveUtils.getString("code" , params , "");
        if(StrUtil.isNotBlank(code)){
            Advertise advertise = advertiseService.getAdvertiseByCode(code);
            if(advertise != null){
                List<AdvertiseImg> imgs = advertiseService.getAdvertiseImgsByPid(advertise.getId());
                if(advertise != null && advertise.getState() == 1){

                    Map param = new HashMap();
                    param.put("advertise", advertise);
                    param.put("imgs", imgs);
                    String html = FreemarkerUtils.parseStr(advertise.getTemplate(), param);

                    Writer out = env.getOut();
                    out.append(html);
                }
            }
        }

    }
}
